<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增渠道代理商')" />
    <th:block th:include="include :: datetimepicker-css" />
    <style>
        .form-group label {
            font-weight: 600;
        }
        .preview-img {
            max-width: 200px;
            max-height: 150px;
            margin-top: 10px;
        }
    </style>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-agent-add" enctype="multipart/form-data">

        <div class="form-group" >
            <label class="col-sm-3 control-label">渠道选择：</label>
            <div class="col-sm-8">
                <select name="channelCode" class="form-control m-b"
                        th:with="type=${@dict.getType('channel_type')}">
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                </select>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label is-required">代理商编号：</label>
            <div class="col-sm-8">
                <input type="text" name="agentName" id="agentName" readonly onclick="openAgent()"
                       placeholder="选择代理商" class="form-control" maxlength="30">
                <i class="fa fa-search" style="margin-top: -22px;margin-right:3px;float:right;"></i>
                <input type="hidden" name="agentId" id="agentId">
            </div>
        </div>

        <!-- 图片上传统一样式：人像面、国徽面、营业执照、银行卡 -->
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">负责人身份证人像面：</label>
            <div class="col-sm-8">
                <input type="file" accept="image/*" class="form-control image-input" data-type="idCardFrontPic" multiple>
                <div class="preview-box"></div>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label is-required">负责人身份证国徽面：</label>
            <div class="col-sm-8">
                <input type="file" accept="image/*" class="form-control image-input" data-type="idCardBackPic" multiple>
                <div class="preview-box"></div>
            </div>
        </div>

        <div class="form-group" id="businessLicensePic">
            <label class="col-sm-3 control-label is-required">营业执照复印件：</label>
            <div class="col-sm-8">
                <input type="file" accept="image/*" class="form-control image-input" data-type="businessLicensePic" multiple>
                <div class="preview-box"></div>
            </div>
        </div>
        <div class="form-group" id="publicAccountPic">
            <label class="col-sm-3 control-label is-required">开户许可证/企业账户截图：</label>
            <div class="col-sm-8">
                <input type="file" accept="image/*" class="form-control image-input" data-type="publicAccountPic" multiple>
                <div class="preview-box"></div>
            </div>
        </div>

        <div class="form-group" id="settleBankCardFrontPic">
            <label class="col-sm-3 control-label is-required">银行卡正面照片：</label>
            <div class="col-sm-8">
                <input type="file" accept="image/*" class="form-control image-input"  id="settleBankCardFrontPic" data-type="settleBankCardFrontPic" multiple>
                <div class="preview-box"></div>
            </div>
        </div>

        <!-- 分润提取模式 -->
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">分润提取模式：</label>
            <div class="col-sm-8">
                <select name="drawPattern" class="form-control" required>
                    <option value="">请选择</option>
                    <option value="1">按天（代发）</option>
                    <option value="2">按月（不代发）</option>
                </select>
            </div>
        </div>

        <!-- 下级代理商分成模式 -->
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">下级代理商分成模式：</label>
            <div class="col-sm-8">
                <select name="profitRuleType" class="form-control" required>
                    <option value="">请选择</option>
                    <option value="0">成本规则</option>
                    <option value="1">SaaS 高签</option>
                    <option value="2">成本比例高签</option>
                    <option value="3">刷宝3.0</option>
                </select>
            </div>
        </div>

        <!-- 下级代理商分成比例 -->
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">下级代理商分成比例（0-100）：</label>
            <div class="col-sm-8">
                <input type="number" name="lowerDivideCent" min="0" max="100" class="form-control" placeholder="请输入整数 0-100" required>
            </div>
        </div>

        <!-- 下级代理商是否独立结算 -->
        <div class="form-group">
            <label class="col-sm-3 control-label is-required">下级代理商是否独立结算：</label>
            <div class="col-sm-8">
                <select name="subProfitBillFlag" class="form-control" required>
                    <option value="">请选择</option>
                    <option value="0">否</option>
                    <option value="1">是</option>
                </select>
            </div>
        </div>


        <!-- 营业执照有效期 -->
        <div class="form-group" id="businessLicenseEndDate">
            <label class="col-sm-3 control-label is-required">营业执照有效期截至时间：</label>
            <div class="col-sm-8">
                <input type="text" name="businessLicenseEndDate" class="form-control" placeholder="例如：2030-12-31" required>
            </div>
        </div>

        <!-- 法人证件有效期（LS 渠道显示） -->
        <div class="form-group" id="legalPersonCertEndDateGroup">
            <label class="col-sm-3 control-label is-required">法人证件结束值：</label>
            <div class="col-sm-8">
                <input type="text" name="legalPersonCertEndDate" class="form-control" placeholder="例如：2030-12-31 长期，则填写“永久有效”">
            </div>
        </div>

        <!-- 法人证件有效起始日期（KDB 渠道显示） -->
        <div class="form-group" id="legalPersonCertPeriodGroup" style="display: none;">
            <label class="col-sm-3 control-label is-required">证件有效起始日期：</label>
            <div class="col-sm-8">
                <input type="text" name="legalPersonCertPeriod" class="form-control" placeholder="例如：20220214-20320214">
            </div>
        </div>
        <!-- 银行名称编码 (仅 KDB 渠道显示) -->
        <div class="form-group" id="bankIdGroup" style="display:none;">
            <label class="col-sm-3 control-label is-required">银行名称编码：</label>
            <div class="col-sm-8">
                <input type="text" name="bankId" id="bankId" class="form-control" placeholder="请输入银行编码">
            </div>
        </div>


    </form>
</div>

<th:block th:include="include :: footer" />
<th:block th:include="include :: datetimepicker-js" />
<script th:inline="javascript">
    var prefix = ctx + "channel/agent";
    var channelType = [[${@dict.getType('channel_type')}]];
    // 图片预览
    document.querySelectorAll(".image-input").forEach(input => {
        input.addEventListener("change", function () {
            const box = this.nextElementSibling;
            box.innerHTML = '';
            [...this.files].forEach(file => {
                const reader = new FileReader();
                reader.onload = function (e) {
                    const img = document.createElement("img");
                    img.src = e.target.result;
                    img.classList.add("preview-img");
                    box.appendChild(img);
                }
                reader.readAsDataURL(file);
            });
        });
    });

    // 提交逻辑
    function submitHandler() {
        if (!$('#form-agent-add').valid()) return;

        var formData = new FormData($('#form-agent-add')[0]);

        // 添加图片内容和类型
        document.querySelectorAll(".image-input").forEach(input => {
            const type = input.dataset.type;
            [...input.files].forEach(file => {
                formData.append("imageFiles", file);
                formData.append("imageTypes", type);
            });
        });

        $.ajax({
            url: prefix + "/add",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            success: function (result) {
                $.operate.successCallback(result);
            },
            error: function () {
                $.modal.alertError("上传失败");
            }
        });
    }

    function openAgent() {
        $.modal.open("选择代理商", ctx + "agentInfo/agentInfo/openAgentInfo", "950", "500");
    }
    // 判断代理商名称长度并控制显示逻辑
    function toggleFieldsByAgentName() {
        const agentName = $('#agentName').val() || '';
        const channelCode = $('select[name="channelCode"]').val();

        if (channelCode === 'KDB') {
            // KDB 渠道银行卡强制显示
            if (agentName.length > 3) {
                $('#businessLicensePic').show();
                $('#businessLicenseEndDate').show();
                $('#publicAccountPic').show();
                $('#settleBankCardFrontPic').show();
            } else {
                $('#businessLicensePic').hide();
                $('#businessLicenseEndDate').hide();
                $('#publicAccountPic').hide();
                $('#settleBankCardFrontPic').show();
            }

        } else {
            // LS 渠道按企业/个人控制
            if (agentName.length > 3) {
                $('#businessLicensePic').show();
                $('#businessLicenseEndDate').show();
                $('#publicAccountPic').show();
                $('#settleBankCardFrontPic').hide();
            } else {
                $('#businessLicensePic').hide();
                $('#businessLicenseEndDate').hide();
                $('#publicAccountPic').hide();
                $('#settleBankCardFrontPic').show();
            }
        }
    }
    // 当页面加载时执行一次
    $(document).ready(function () {
        toggleFieldsByAgentName();

        // 添加输入框失焦或变化事件监听
        $('#agentName').on('input change  blur', function () {
            toggleFieldsByAgentName();
        });

        $('select[name="channelCode"]').on('change', function () {
            toggleFieldsByChannel();
        });

        function toggleFieldsByChannel() {
            const channelCode = $('select[name="channelCode"]').val();

            if (channelCode === 'KDB') {
                // 1️⃣ 隐藏分润相关字段并设置默认值
                $('select[name="drawPattern"]').val("1").closest('.form-group').hide();
                $('select[name="profitRuleType"]').val("0").closest('.form-group').hide();
                $('input[name="lowerDivideCent"]').val("0").closest('.form-group').hide();
                $('select[name="subProfitBillFlag"]').val("0").closest('.form-group').hide();

                // 2️⃣ KDB 渠道银行卡上传永远显示
                $('#settleBankCardFrontPic').show();

                // 3️⃣ 切换法人证件日期输入框
                $('#legalPersonCertEndDateGroup').hide();
                $('#legalPersonCertPeriodGroup').show();

                //显示银行名称编码
                $('#bankIdGroup').show();
            } else {
                // 显示所有分润相关字段
                $('select[name="drawPattern"]').closest('.form-group').show();
                $('select[name="profitRuleType"]').closest('.form-group').show();
                $('input[name="lowerDivideCent"]').closest('.form-group').show();
                $('select[name="subProfitBillFlag"]').closest('.form-group').show();

                // 切换法人证件日期输入框
                $('#legalPersonCertEndDateGroup').show();
                $('#legalPersonCertPeriodGroup').hide();

                toggleFieldsByAgentName(); // 恢复对公/对私显示逻辑

                // 隐藏银行名称编码
                $('#bankIdGroup').hide();
            }
        }

    });
</script>
</body>
</html>
